<script setup lang="ts">
import { computed, defineProps, defineEmits, ref } from 'vue';

import { ElIcon } from 'element-plus';

// 导入子组件
import ResponsiveWrapper from './ResponsiveWrapper.vue';

const props = defineProps({
  isEditMode: {
    type: Boolean,
    default: false,
  },
  layoutItems: {
    type: Array,
    default: () => [],
  },
  gridUnitSize: {
    type: Number,
    default: 0,
  },
  canvasHeight: {
    type: Number,
    default: 0,
  },
  selectedItem: {
    type: Object,
    default: null,
  },
  draggedItem: {
    type: Object,
    default: null,
  },
  componentMap: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits([
  'drop',
  'dragover',
  'startDrag',
  'configureItem',
  'removeItem',
  'startResize',
]);

const canvasRef = ref<HTMLElement>();

const gridToPixel = (gridValue: number) => {
  return gridValue * props.gridUnitSize;
};

const getComponentByType = (type: string) => {
  return props.componentMap[type as keyof typeof props.componentMap];
};
</script>

<template>
  <div
    ref="canvasRef"
    class="canvas-area relative rounded bg-white"
    :style="{
      width: '100%',
      height: `${canvasHeight}px`,
    }"
    @drop="($event) => emit('drop', $event)"
    @dragover="($event) => emit('dragover', $event)"
  >
    <!-- 栅格背景 - 正方形网格 -->
    <div
      v-if="isEditMode"
      class="pointer-events-none absolute inset-0"
      :style="{
        backgroundImage: `
          linear-gradient(to right, #ddd 1px, transparent 1px),
          linear-gradient(to bottom, #ddd 1px, transparent 1px)
        `,
        backgroundSize: `${gridUnitSize}px ${gridUnitSize}px`,
      }"
    ></div>

    <!-- 组件 -->
    <div
      v-for="(item, index) in layoutItems"
      :key="item.id"
      class="layout-item absolute rounded-lg border bg-white shadow-sm transition-all"
      :class="{
        'border-blue-400 shadow-lg': isEditMode,
        'border-red-400 shadow-lg': isEditMode && selectedItem?.id === item.id,
        'hover:shadow-md': !isEditMode,
        'cursor-move': isEditMode,
        'cursor-pointer': isEditMode,
        dragging: draggedItem?.id === item.id,
        selected: selectedItem?.id === item.id,
      }"
      :style="{
        left: `${gridToPixel(item.gridX)}px`,
        top: `${gridToPixel(item.gridY)}px`,
        width: `${gridToPixel(item.gridWidth)}px`,
        height: `${gridToPixel(item.gridHeight)}px`,
        zIndex: draggedItem?.id === item.id ? 50 : 10 + index,
      }"
      @mousedown="($event) => emit('startDrag', $event, item)"
    >
      <!-- 编辑模式控制按钮 -->
      <div
        v-if="isEditMode"
        class="item-controls absolute -right-2 -top-2 z-10 flex space-x-1"
      >
        <el-button
          size="small"
          circle
          type="primary"
          title="配置组件"
          @click="($event) => emit('configureItem', $event, item)"
        >
          <ElIcon>
            <component is="Setting" />
          </ElIcon>
        </el-button>
        <el-button
          size="small"
          circle
          type="danger"
          title="删除组件"
          @click="($event) => emit('removeItem', $event, item.id)"
        >
          <ElIcon>
            <component is="Close" />
          </ElIcon>
        </el-button>
      </div>

      <!-- 栅格信息显示 -->
      <div
        v-if="isEditMode"
        class="grid-info absolute left-1 top-1 rounded bg-blue-600 px-1 text-xs text-white opacity-75"
      >
        {{ item.gridWidth }}×{{ item.gridHeight }}
      </div>

      <!-- 响应式组件内容 -->
      <ResponsiveWrapper
        :width="gridToPixel(item.gridWidth)"
        :height="gridToPixel(item.gridHeight)"
      >
        <component :is="getComponentByType(item.type)" :config="item.config" />
      </ResponsiveWrapper>

      <!-- 调整大小手柄 -->
      <template v-if="isEditMode">
        <!-- 右边 -->
        <div
          class="resize-handle resize-handle-right"
          @mousedown="($event) => emit('startResize', $event, item, 'right')"
        ></div>
        <!-- 底边 -->
        <div
          class="resize-handle resize-handle-bottom"
          @mousedown="($event) => emit('startResize', $event, item, 'bottom')"
        ></div>
        <!-- 右下角 -->
        <div
          class="resize-handle resize-handle-bottom-right"
          @mousedown="($event) => emit('startResize', $event, item, 'bottom-right')"
        ></div>
      </template>
    </div>

    <!-- 空状态 -->
    <div
      v-if="layoutItems.length === 0"
      class="empty-state absolute inset-0 flex items-center justify-center"
    >
      <div class="text-center">
        <ElIcon size="48" class="mb-4 text-gray-300">
          <component is="Grid" />
        </ElIcon>
        <p class="mb-2 text-lg text-gray-500">
          {{ isEditMode ? '24栅格设计画布' : '暂无内容' }}
        </p>
        <p class="text-sm text-gray-400">
          {{
            isEditMode
              ? '从上方拖拽组件到此处，支持栅格对齐和响应式缩放'
              : '点击"开始设计"添加组件'
          }}
        </p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.canvas-area {
  position: relative;
}

.layout-item {
  overflow: hidden;
  user-select: none;
}

.layout-item.dragging {
  border: 2px solid #409eff;
  box-shadow: 0 8px 25px rgb(0 0 0 / 15%);
  opacity: 0.8;
  transform: rotate(2deg);
}

.layout-item.selected {
  border: 2px solid #f56565 !important;
  box-shadow: 0 0 0 2px rgb(245 101 101 / 20%);
}

.layout-item.selected::before {
  position: absolute;
  top: -8px;
  left: 8px;
  z-index: 20;
  padding: 2px 6px;
  font-size: 10px;
  color: white;
  content: '已选中';
  background: #f56565;
  border-radius: 4px;
}

.item-controls {
  opacity: 0.7;
  transition: all 0.2s;
}

.layout-item:hover .item-controls {
  opacity: 1;
  transform: scale(1.05);
}

.item-controls .el-button {
  box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
}

.item-controls .el-button:hover {
  transform: scale(1.1);
}

.grid-info {
  opacity: 0;
  transition: opacity 0.2s;
}

.layout-item:hover .grid-info {
  opacity: 0.9;
}

/* 调整大小手柄 */
.resize-handle {
  position: absolute;
  background: #409eff;
  opacity: 0;
  transition: opacity 0.2s;
}

.layout-item:hover .resize-handle {
  opacity: 0.8;
}

.resize-handle:hover {
  opacity: 1 !important;
}

.resize-handle-right {
  top: 0;
  right: -3px;
  width: 6px;
  height: 100%;
  cursor: ew-resize;
}

.resize-handle-bottom {
  bottom: -3px;
  left: 0;
  width: 100%;
  height: 6px;
  cursor: ns-resize;
}

.resize-handle-bottom-right {
  right: -3px;
  bottom: -3px;
  width: 12px;
  height: 12px;
  cursor: nw-resize;
  border-radius: 0 0 6px;
}
</style>